package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.DisplayUtil;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.activity.TeamCircleActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.FoundAppData;
import com.jp.knowledge.model.FoundBanner;
import com.jp.knowledge.model.FundAppHome;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InteractDataModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.FoundGridItem;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/4/18.
 */

public class FindFragment extends BaseFragment implements ResultSubscriber.OnResultListener {

    private static final int GET_BANNER_CODE = 0x01;
    private final static int GET_APPDATA_CODE = 0x02;

    private Context mContext;
    private View contentView;
    private Banner bannerView;
    private LinearLayout teamCircleBtn;
    private TextView updateCount;
    private FrameLayout updateHead;
    private ImageView updateImg;
    private LinearLayout mainLayout;

    private String appCachePath;
    private String bannerCachePath;
    private FileCacheManager cacheManager;

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast  localBroadCast;

    private List<FundAppHome> appDatas;
    private List<com.jp.knowledge.model.Banner> banners;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        appCachePath = mContext.getCacheDir() + "/findAppData.dat";
        bannerCachePath = mContext.getCacheDir() + "/findBannerData.dat";
        cacheManager = new FileCacheManager();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null) {
            contentView = View.inflate(mContext, R.layout.fragment_find, null);
            bannerView = (Banner) contentView.findViewById(R.id.banner_view);
            teamCircleBtn = (LinearLayout) contentView.findViewById(R.id.find_team_circle);
            mainLayout = (LinearLayout) contentView.findViewById(R.id.find_content_view);
            updateCount = (TextView) contentView.findViewById(R.id.team_circle_count);
            updateHead = (FrameLayout) contentView.findViewById(R.id.team_circle_head);
            updateImg = (ImageView) contentView.findViewById(R.id.team_circle_icon);
            teamCircleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(mContext, TeamCircleActivity.class));
                    LatestStateService.clearBadge();
                }
            });
            bannerView.getLayoutParams().height = (int) (DensityUtil.getScreenWidth() * 302f / 922f + 0.5f);
            bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            bannerView.setIndicatorGravity(BannerConfig.CENTER);
            bannerView.setImageLoader(new ImageLoader(){
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    String imagePath = ((com.jp.knowledge.model.Banner)path).getSrc();
                    if("R.mipmap.imaging".equals(imagePath))
                        imageView.setImageResource(R.mipmap.imaging);
                    else
                        Glide.with(mContext).load(imagePath).error(R.mipmap.morentutouxiang).into(imageView);
                }
            });
            bannerView.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    com.jp.knowledge.model.Banner banner = banners.get(position);
                    CommandReceiver receiver = new CommandReceiver.Builder(mContext)
                            .withCompanyId(banner.getCommpanyId())
                            .withRecordId(banner.getRecordId()).build();
                    Command command = Command.create(banner.getCommand(), receiver);
                    CommandInvoker.executeCommand(command);
                }
            });

            initBroadcast();

            initHead(contentView);
            readBannerCache();
            readAppCache();
            setTeamCircleBtn();
        }
        return contentView;
    }

    private void setTeamCircleBtn(){
        UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
        if(userData != null && userData.getCompanyList() != null && userData.getCompanyList().size() > 0) {
            List<OrganizaModel> companyList = userData.getCompanyList();
            for(OrganizaModel organizaModel : companyList){
                if(organizaModel.getCompanyState() != 1
                        || (organizaModel.getAuditStete() != 0 && organizaModel.getAuditStete() != 2)){
                    teamCircleBtn.setVisibility(View.VISIBLE);
                    return;
                }
            }
        }
        teamCircleBtn.setVisibility(View.GONE);
    }

    private void initBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.GET_LOGIN_INFO.equals(action)
                        || LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)) {
                    if (appDatas != null)
                        setAppView(appDatas);
                    getAppData();
                    setTeamCircleBtn();
                } else if(LocalBroadCast.GET_INTERACT_DATA_CODE.equals(action)){
                    InteractDataModel dataModel = LatestStateService.getInteractDataModel();
                    if(dataModel == null) {
                        updateCount.setVisibility(View.GONE);
                        updateHead.setVisibility(View.GONE);
                        return;
                    }
                    if(dataModel.getCount() > 0){
                        updateCount.setVisibility(View.VISIBLE);
                        updateCount.setText(dataModel.getCount() + "");
                    } else if(dataModel.getCount() == 0){
                        updateCount.setVisibility(View.GONE);
                    }
                    if(dataModel.getBadge() == null
                            || dataModel.getBadge().getRecordId() == null
                            || dataModel.getBadge().getRecordId().trim().length() == 0){
                        updateHead.setVisibility(View.GONE);
                    } else{
                        updateHead.setVisibility(View.VISIBLE);
                        ImageLoadUtil.load(mContext, dataModel.getBadge().getPortrait(), updateImg);
                    }
                }
            }
        });
        IntentFilter  intent = new IntentFilter();
        intent.addAction(LocalBroadCast.GET_LOGIN_INFO);
//        intent.addAction(LocalBroadCast.USER_DATA_CHANGE);
        intent.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        intent.addAction(LocalBroadCast.GET_INTERACT_DATA_CODE);
        localBroadcastManager.registerReceiver(localBroadCast,intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadCast);
    }

    @Override
    protected void initHead(View mView) {
        super.initHead(mView);
        topName.setText("发现");
        rightIcon.setVisibility(View.GONE);
        rightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchActivity.class);
                intent.putExtra("action",1);
                intent.putExtra("level",1);
                intent.putExtra("type",1);
                intent.putExtra("sourceType",2);
                startActivity(intent);
            }
        });
    }

    private void setBannerData(FoundBanner data){
        if(banners == null)
            banners = new ArrayList<>();
        else
            banners.clear();
        if(data == null || data.getBanner() == null || data.getBanner().size() == 0) {
            com.jp.knowledge.model.Banner banner = new com.jp.knowledge.model.Banner();
            banner.setSrc("R.mipmap.imaging");
            banners.add(banner);
            bannerView.update(banners);
        } else {
            banners.addAll(data.getBanner());
            bannerView.update(banners);
        }
    }

    private void setAppView(List<FundAppHome> data){
        mainLayout.removeAllViews();
        if(data != null) {
            for (int i = 0; i < data.size(); i++) {
                FundAppHome home = data.get(i);
                List<FoundAppData> tempDatas = home.getGropuApps();
                List<FoundAppData> appDatas = new ArrayList<>();
                for (FoundAppData appData : tempDatas)
                    if (appData.getIndexSort() != 10)
                        appDatas.add(appData);
                home.setGropuApps(appDatas);
                FoundGridItem gridItem = new FoundGridItem(mContext);
                gridItem.setHomeData(home);
                if (i != 0)
                    mainLayout.addView(getLineView());
                mainLayout.addView(gridItem);
            }
        }
    }

    private View getLineView(){
        View view = new View(mContext);
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)mContext.getResources().getDimension(R.dimen.space_middle)));
        view.setBackgroundResource(R.color.found_item_line);
        return view;
    }

    private void readBannerCache(){
        Observable.create(new Observable.OnSubscribe<FoundBanner>() {
            @Override
            public void call(Subscriber<? super FoundBanner> subscriber) {
                FoundBanner appData = (FoundBanner) cacheManager.readObject(bannerCachePath);
                subscriber.onNext(appData);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<FoundBanner>() {
                    @Override
                    public void onCompleted() {
                        getBannerData();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(FoundBanner data) {
                        setBannerData(data);
                    }
                });
    }

    private void readAppCache(){
        Observable.create(new Observable.OnSubscribe<List<FundAppHome>>() {
            @Override
            public void call(Subscriber<? super List<FundAppHome>> subscriber) {
                List<FundAppHome> appData = (List<FundAppHome>) cacheManager.readObject(appCachePath);
                subscriber.onNext(appData);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<FundAppHome>>() {
                    @Override
                    public void onCompleted() {
                        getAppData();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<FundAppHome> data) {
                        if(data != null){
                            appDatas = data;
                            setAppView(appDatas);
                        }
                    }
                });
    }

    private void getBannerData(){
        JsonObject param = new JsonObject();
        param.addProperty("action", 2);
        HttpHelper.getInstance(mContext).discoverData(param, GET_BANNER_CODE, this);
    }

    private void getAppData(){
        JsonObject param = new JsonObject();
        param.addProperty("type",2);
        HttpHelper.getInstance(mContext).discoverApps(param, GET_APPDATA_CODE, this);
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == GET_BANNER_CODE){
            FoundBanner foundBanner = data.getEntity(FoundBanner.class);
            setBannerData(foundBanner);
            saveCache(foundBanner, bannerCachePath);
        } else if(requestType == GET_APPDATA_CODE){
            List<FundAppHome> list = data.getList(FundAppHome.class);
            appDatas = list;
//            if(appDatas != null) {
                setAppView(appDatas);
                saveCache(appDatas, appCachePath);
//            }
        }
    }
}
